<script lang="ts" setup>
import { ref, computed } from "vue";
import type { FormSchema } from "@/typings/dynamic-search";
import { NCard, NForm, NButton, NGrid, NGridItem, NIcon, type FormInst } from "naive-ui";
import { ArrowDown, ArrowUp } from "@vicons/ionicons5";
import { getComponent } from "./index";
import { shallowRef } from "vue";
import { useI18n } from "@/hooks/useI18n";

const { t } = useI18n();

interface FormProps {
  labelWidth: number | string | "auto";
  labelPlacement: "left" | "right";
  formConfig: FormSchema[];
  defaultShowCount?: number; //默认展示多少个项
}

const props = withDefaults(defineProps<FormProps>(), {
  defaultShowCount: 6,
});

const emits = defineEmits<{
  search: [];
  cancel: [];
}>();

const form = ref<FormInst | null>();

const showSchema = shallowRef<FormSchema[]>([]);

const isShowMore = computed(() => props.formConfig.length > props.defaultShowCount);

const expand = ref<boolean>(false);

const getShowSchema = (count: number) => {
  showSchema.value = props.formConfig.slice(0, count);
};

getShowSchema(props.defaultShowCount);

/** 生成 Form 表单属性 */
const genProps = () => {
  const { formConfig, defaultShowCount, ...formInsProp } = props;
  return { ...formInsProp, ref: form } as Partial<typeof NForm>;
};

/** 展开收起 */
const toggleExpand = () => {
  expand.value = !expand.value;
  if (expand.value) {
    getShowSchema(props.formConfig.length);
  } else {
    getShowSchema(props.defaultShowCount);
  }
};

/** 点击查询 */
const toggleSearch = () => {
  emits("search");
};

/** 点击重置 */
const toggleCancel = () => {
  emits("cancel");
};

defineExpose({ form });
</script>

<template>
  <NCard>
    <NForm v-bind="genProps()">
      <NGrid cols="1 s:1 m:2 l:3 xl:3 2xl:4" responsive="screen" x-gap="30">
        <template v-for="item in showSchema">
          <NGridItem>
            <component :is="getComponent(item.type)" :config="item" />
          </NGridItem>
        </template>
      </NGrid>
      <div class="flex justify-end gap-x-4 pr-4">
        <NButton @click="toggleCancel">{{ t("common.reset") }}</NButton>
        <NButton type="primary" @click="toggleSearch">{{ t("common.search") }}</NButton>
        <NButton text icon-placement="right" v-if="isShowMore" @click="toggleExpand">
          <span>{{ expand ? t("common.collapse") : t("common.expand") }}</span>
          <template #icon>
            <NIcon>
              <ArrowUp v-if="expand" />
              <ArrowDown v-else />
            </NIcon>
          </template>
        </NButton>
      </div>
    </NForm>
  </NCard>
</template>

<style lang="less" scoped></style>
